package com.javabi.codegenerator.java.object.executable.method;

import com.javabi.codegenerator.java.model.bean.JavaModelBean;
import com.javabi.codegenerator.java.model.bean.JavaModelBeanField;
import com.javabi.codeobject.java.block.IJavaNamedType;
import com.javabi.codeobject.java.block.codeblock.IJavaCodeLines;
import com.javabi.codeobject.java.block.codeblock.JavaCodeLines;
import com.javabi.codeobject.java.block.method.JavaMethod;

public class ExecutableMethod extends JavaMethod {

	private final JavaModelBean bean;

	public ExecutableMethod(JavaModelBean bean) {
		super(bean.getName(), bean.getReturnType());
		this.bean = bean;

		// Parameters
		for (JavaModelBeanField field : bean.getFieldList()) {
			getParameters().add(field.getName(), field.getType());
		}

		// Contents
		setMethodContents();
	}

	private void setMethodContents() {
		String interfaceType = bean.getInterfaceType().getSimpleName(true);
		String instanceType = bean.getType().getSimpleName(true);

		IJavaCodeLines code = new JavaCodeLines();
		code.line(interfaceType + " bean = new " + instanceType + "(" + getParameterNames() + ");");
		if (getReturnType().isVoid()) {
			code.line("getExecutor().execute(bean);");
		} else {
			code.line("return getExecutor().execute(bean);");
		}
		setContents(code);
	}

	private String getParameterNames() {
		boolean comma = false;
		StringBuilder names = new StringBuilder();
		for (IJavaNamedType parameter : getParameters()) {
			if (comma) {
				names.append(", ");
			}
			comma = true;
			names.append(parameter.getName().toLower());
		}
		return names.toString();
	}
}
